package com.zbs.framework.common.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.zbs.framework.common.config.MsmConfigSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Map;

;

/**
 * @author 头都给你打歪
 * @date 2020/7/30 14:54
 *
 * 阿里云短信服务
 */
@Configuration
@Component
public class AlibabaSmsUtil {

    @Autowired
    private MsmConfigSettings msmConfigSettings;


    public boolean send(String templateCode, Map<String, Object> param, String phone) throws ClientException {
       return this.send(this.msmConfigSettings.getSignName(),templateCode,param,phone);
    }

    public boolean send(String signName,String templateCode, Map<String, Object> param, String phone) throws ClientException {
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile(this.msmConfigSettings.getRegionId(), this.msmConfigSettings.getAccessKeyId(), this.msmConfigSettings.getSecret());
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setSysMethod(MethodType.POST);
        request.setPhoneNumbers(phone);//手机号
        request.setSignName(signName);//申请阿里云 签名名称
        request.setTemplateCode(templateCode);//验证码数据，转换json数据传递
        request.setTemplateParam(JSONObject.toJSONString(param));
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK");
    }


}
